import 'dart:convert';
import 'dart:developer';

import 'package:flutter/foundation.dart';
import 'package:zhibao_flutter/main.dart';
import 'package:zhibao_flutter/util/check/check.dart';
import 'package:zhibao_flutter/util/func/log.dart';
import 'package:zhibao_flutter/util/func/tips_util.dart';
import 'package:zhibao_flutter/util/http/http.dart';

Map getKeys(obj) {
  Map requestBody;
  if (obj is BaseRequest) {
    requestBody = jsonDecode(jsonEncode(obj));

    for (final k in requestBody.keys.toList(growable: false)) {
      final v = requestBody[k];
      if (v == null || v == 'null') {
        requestBody.remove(k);
      }
    }
  } else {
    requestBody = obj;
  }
  return requestBody;
}

Map netError(String url, e, requestBody) {
  Map eMap = {'code': '1', 'msg': TipsUtil.netError, 'data': url};
  LogUtil.d('HTTP_REQUEST_ERROR::${e.toString()}');
  LogUtil.d('HTTP_REQUEST_RESULT::${eMap.toString()}');
  if (mapNoEmpty(requestBody)) {
    try {
      String reqBody = jsonEncode(requestBody);
      LogUtil.d('HTTP_REQUEST_BODY::[ERROR]::$reqBody');
    } catch (e) {
      LogUtil.d("HTTP_REQUEST_BODY::格式化有点小错误");
    }
  }
  return eMap;
}

logPrint(reqType, query, id, httpUrl, requestBody, body) {
  String? queryStr = reqType == ReqType.getPin ? query?.toString() : '';
  LogUtil.d('HTTP_REQUEST_URL::[$id]::$httpUrl${queryStr ?? ''}');
  LogUtil.d('HTTP_REQUEST_TYPE::[$id]::${reqType ?? ''}');
  String date = MyDate.formatTimeStampToString(
      DateTime.now().millisecondsSinceEpoch ~/ 1000, 'yyyy-MM-dd HH:mm:ss');
  LogUtil.d('HTTP_REQUEST_TIME::[$id]::$date');
  if (mapNoEmpty(requestBody)) {
    String reqBody = jsonEncode(requestBody);
    LogUtil.d('HTTP_REQUEST_BODY::[$id]::$reqBody');
  }
  LogUtil.d('HTTP_RESPONSE_BODY::[$id]::Type[${body.runtimeType}]::$body');
}

errorLog(url, e, [body]) {
  q1Logger.info('request.url：$url');
  try {
    if (body != null) debugPrint('request.body：${jsonEncode(body)}');
  } catch (e) {
    q1Logger.info('request.body：$body');
  }
  q1Logger.info('response.error：$e');
}
